<template>
	<view class="order">
		<view class="product-list">
			<view v-for="product in products" :key="product.id" class="product-item">
				<image :src="product.image" class="product-image" mode="aspectFit" />
				<view class="shangpin">
					<view class="product-name">{{ product.goodsName }}</view>

					<view class="product-info">单价: ¥{{ product.goodsMoney }}</view>
					<view class="product-info">数量: {{ product.goodsNumber }}</view>
					<view class="product-total">原价: ¥{{ product.totalMoney | "0.00" }}</view>
					<!-- <view class="payMoney">优惠价: ¥{{ product.payMoney | "0.00" }}</view> -->

				</view>

			</view>
		</view>

		<view class="footer">
			<view class="total-container">
				<view class="total">
					<view class="total-label">订单编号:</view>
					<view class="total-amount">{{orderId}}</view>
				</view>
			</view>
			<view class="total-container">
				<view class="total">
					<view class="total-label">订单总计:</view>
					<view class="total-amount">¥{{ total | "0.00" }}</view>
					<!-- <view class="total-label">实付款:</view>
					<view class="total-amount">¥{{ payMoney | "0.00" }}</view> -->
				</view>

			</view>
			<view class="order-item">
				<p class="title">收货地址:</p>
				<view class="address-textarea">
					{{address||"无收货地址"}}
				</view>
			</view>
			<button class="pay" v-if="state=='0'" @click="fukuan">付款</button>
			<button class="pay" style="background-color: red;" v-if="state=='0'" @click="shanchu">删除订单</button>
			<button class="pay" v-if="state=='2'" @click="shouhuo">确认收货</button>
			<button class="pay" v-if="paystate==1&&state!='2'" @click="refund">申请退款</button>
		</view>
	</view>
</template>

<script>
	import {
		waitpaywx,
		refundbut,
		successorder,
		deletedwaitorderlist
	} from '../../api/order/order.js'
	export default {

		data() {
			return {
				address: '',
				products: [],
				total: 0,
				state: "",
				paystate: null,
				orderId: ''
			};
		},
		onLoad(options) {
			this.loadOrderDetails(options.orderId);
		},
		created() {
			// 组件创建时加载订单详情并计算 usepoints
			this.loadOrderDetails();
		},
		methods: {
			// 计算 usepoints 的方法
			calculateUsepoints() {
				const orderData = uni.getStorageSync('orderDetail');
				if (orderData && orderData.data) {
					// 使用 reduce 方法计算 usepoints
					this.usepoints = orderData.data.reduce((accumulator, currentElement) => {
						return accumulator + currentElement.payPoints;
						//  console.log("usepoints", this.usepoints)
					}, 0);
				} else {
					// 如果没有数据或数据格式不正确，设置 usepoints 为 0
					this.usepoints = 0;
				}
			},

			// 加载订单详情的方法
			loadOrderDetails() {
				// 从本地存储获取订单详情数据
				const orderData = uni.getStorageSync('orderDetail');
				// console.log("订单详情", orderData)


				// 检查 orderData 是否存在
				if (orderData) {
					// 设置地址、产品、总计、订单ID、状态和支付状态等属性
					this.address = orderData.userAddress;
					this.products = orderData.data;
					this.total = orderData.total;
					this.orderId = orderData.orderId;
					this.state = orderData.state;
					this.paystate = orderData.paystate;
					this.payMoney = orderData.payMoney;
					// 调用 calculateUsepoints 方法计算 usepoints
					this.calculateUsepoints();

				} else {
					// 如果没有订单详情数据，设置 usepoints 为 0 并处理其他属性
					this.usepoints = 0;
					// 可能还需要处理其他属性的默认值或错误状态
				}
			},
			fukuan() {
				//  console.log("执行付款操作");
				//  console.log("地址", this.address);
				//  console.log("产品", this.products);
				//  console.log("总价", this.total);
				let userInfo = uni.getStorageSync("openid");
				//  console.log("openid", userInfo); // 这里假设您想打印 openid
				let payData = {
					totalMoney: this.payMoney,
					data: this.products,
					userInfo: userInfo, // 使用从 storage 中获取的 openid
					address: this.address,
					usepoints: this.usepoints,
					orderId: this.orderId
				};
				//  console.log("payData", payData);
				waitpaywx(payData).then(res => {
					//  console.log('支付请求成功，返回数据：', res.data);
					this.requestPaymentWithWx(res.data);

				}).catch(err => {
					console.error('支付请求失败：', err);
				});
			},
			// 确认收货
			shouhuo() {
				//  console.log("订单:", uni.getStorageSync('orderDetail'));
				let data = uni.getStorageSync('orderDetail')
				successorder(data).then(res => {
					uni.showToast({
						title: '确认收货成功',
						icon: 'success',
					});
					//  console.log("确认收货成功", res)
					setTimeout(function() {
						uni.switchTab({
							url: '/pages/me/me'
						});
					}, 1000); // 1000毫秒等于1秒

				}).catch(err => {
					//  console.log("请求失败", err)
					uni.showToast({
						title: '请求失败',
						icon: 'none'
					});
				})
			},
			// 删除
			shanchu(){
				let data = {
					orderId: this.orderId,
				}
				deletedwaitorderlist(data).then(res => {
					uni.navigateBack({
					delta: 1
					})
					uni.showToast({
						title: '删除成功',
						icon: 'success',
					});
					
				}).catch(err => {
					uni.showToast({
						title: '删除失败',
						icon: 'none',
						});
						
				})
			},
			//退款
			refund() {
				let openId = uni.getStorageSync("openid");
				if (!openId) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}
				let data = {
					orderId: this.products[0].orderId,
					openId: openId
				}
				refundbut(data).then(res => {
					//  console.log("退款成功", res)
					uni.showToast({
						title: '申请退款成功',
						icon: 'success',
					});
					setTimeout(function() {
						uni.switchTab({
							url: '/pages/me/me'
						});
					}, 1000); // 1000毫秒等于1秒

				}).catch(err => {
					//  console.log("请求失败", err)
					uni.showToast({
						title: '请求失败',
						icon: 'none',
					});
				})
			},
			requestPaymentWithWx(data) {
				// 调用微信支付
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: String(data.msg.TimeStamp),
					nonceStr: data.msg.nonce_str,
					package: "prepay_id=" + data.msg.responseObject.xml
						.prepay_id._cdata + "",
					signType: 'MD5',
					paySign: data.msg.sign,
					success: function(res) {
						//  console.log('success:' + JSON.stringify(res));
					},
					fail: function(err) {
						//  console.log('fail:' + JSON.stringify(err));
					},
					success: function(res) {
						//  console.log('微信支付成功：', res);
						// 支付成功后的操作，例如更新订单状态等
						// 可以在这里调用更新订单状态的函数
						setTimeout(function() {
							uni.switchTab({
								url: '/pages/me/me'
							});
						}, 1000); // 1000毫秒等于1秒

					},
					fail: function(err) {
						//  console.log('微信支付失败：', err);
						// 支付失败后的操作
						uni.showToast({
							title: '微信支付失败',
							icon: 'none'
						});
					}
				});
			}
		}
	};
</script>

<style scoped>
	.order {
		height: 100vh;
		padding: 20px 0px 50px 0px;
		background-color: #f8f8f8;
		font-size: 14px;
	}

	.product-list {
		display: flex;
		flex-direction: column;
		gap: 20px;
	}

	.product-item {
		display: flex;
		border: 1px solid #ddd;
		border-radius: 10px;
		padding: 15px;
		background-color: #ffffff;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		align-items: center;
		/* justify-content: center; */
	}

	.product-image {
		width: 80px;
		height: 80px;
		border-radius: 10px;
		margin-right: 15px;
	}

	.shangpin {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		flex: 1;
	}

	.product-name {
		font-weight: bold;
		font-size: 16px;
		color: #333;
		margin-bottom: 5px;
	}

	.product-info {
		font-size: 14px;
		color: #666;
		margin-bottom: 5px;
	}

	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		padding: 10px 20px 0px 20px;
		box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
		/* z-index: 1000; */
	}

	.order-item {
		display: flex;
		/* flex-direction: column; */
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20px;
	}

	.title {
		font-size: 16px;
		font-weight: bold;
		color: #333;
	}

	.address-textarea {
		padding: 10px;
		border-radius: 10px;
		border: 1px solid #ddd;
		color: #333;
		font-size: 14px;
		resize: none;
	}

	.total-container {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.total {
		display: flex;
		justify-content: space-between;
		width: 100%;
	}

	.total-label {
		font-size: 16px;
		font-weight: bold;
		color: #333;
	}

	.product-total {
		color: #04BE02;
	}

	.total-amount {
		font-size: 18px;
		font-weight: bold;
		color: #e91e63;
	}

	.pay {
		background-color: #04BE02;
		margin-bottom: 20px;
		color: white
	}

	.payMoney {
		color: red
	}
</style>